package com.yhg.backend.controller;

import com.yhg.backend.pojo.User;
import com.yhg.backend.vo.Result;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;



@RestController
@RequestMapping("/user")
@Tag(name = "用户管理")
public class UserController {

    /**
     * 登录
     *
     * @param user        提交的用户数据，包含用户名和密码
     * @param httpSession HttpSession
     * @return Result<Object>
     */
    @PostMapping("/login")
    @Operation(summary = "用户登录")
    public Result<Object> login(@RequestBody User user, HttpSession httpSession) {
        System.out.println("收到登录请求: " + (user != null ? user.getUsername() : "null"));
        
        if (user == null || !"123456".equals(user.getPassword())) {
            System.out.println("登录失败: 用户名或密码错误");
            return Result.fail("用户名或密码错误");
        }

        httpSession.setAttribute("currentUser", user.getUsername());
        System.out.println("用户登录成功: " + user.getUsername());
        System.out.println("会话ID: " + httpSession.getId());
        
        return Result.success();
    }

    /**
     * 获取用户名
     *
     * @param httpSession HttpSession
     * @return String
     */
    @GetMapping("/getUsername")
    @Operation(summary = "获得用户信息")
    public Result<String> getUsername(HttpSession httpSession) {
        String username = (String) httpSession.getAttribute("currentUser");
        System.out.println("获取用户名请求，会话ID: " + httpSession.getId());
        System.out.println("当前用户: " + username);
        
        return Result.success(username);
    }

    /**
     * 退出登录
     *
     * @param httpSession HttpSession
     * @return Result<Object>
     */
    @GetMapping("/logout")
    @Operation(summary = "退出登录")
    public Result<Object> logout(HttpSession httpSession) {
        httpSession.removeAttribute("currentUser");
        return Result.success();
    }

}
